import { batchDate } from "./date";
import { dbName } from "./constant";
import logger from "../utils/logger";
import { getDBReady } from "./dbReady";
/**
 * 新增某日账单项
 * @param {DB.Date & DB.ClockRecord} { dateId, eventName, amount, changeType } 日期id：日期对应的记录id 事件名称 变动金额 变动类型
 * @return.data boolean true 成功，false 失败
 */
export async function addClockRecord({ dateId, time } : DB.DateId & DB.ClockRecord) : Promise<boolean> {
	if (!getDBReady()) return null;
	return new Promise((resolve) => {
		const sql = `
		      INSERT INTO clocks (dateId, time) 
		      VALUES ('${dateId}', '${time}')`;

		plus.sqlite.executeSql({
			name: dbName,
			sql: [sql],
			success: async () => {
				logger('添加成功');
				resolve(true);
			},
			fail: (e) => {
				logger('添加失败:', e.message);
				resolve(null);
			}
		});
	});
}
export async function deleteClockRecord(clockId : DB.ClockId['clockId']) : Promise<boolean> {
	if (!getDBReady()) return null;
	return new Promise((resolve) => {
		const sql = `
		      delete from clocks where clockId='${clockId}'`;

		plus.sqlite.executeSql({
			name: dbName,
			sql: [sql],
			success: async () => {
				logger('删除成功');
				resolve(true);
			},
			fail: (e) => {
				logger('添加失败:', e.message);
				resolve(null);
			}
		});
	});
}
/**
 * 查询某天打卡记录
 * @param number 日期id：日期对应的记录id
 * @return  打卡集合
 */
export async function queryClockRecord(dateId : DB.DateId['dateId']) : Promise<Array<DB.ClockTimeSource>> {
	if (!getDBReady()) return null;
	return new Promise<Array<DB.ClockTimeSource>>((resolve) => {
		const sql = `SELECT * FROM clocks WHERE dateId='${dateId}' ORDER BY time ASC`;

		plus.sqlite.selectSql({
			name: dbName,
			sql: sql,
			success: (res) => {
				logger('查询成功:', res);
				resolve(res ?? null);
			},
			fail: (e) => {
				logger(e)
				resolve(null);
			}
		});
	});
}


/**
 * 查询某个时间段所有打卡
 * @param {{ startDate : string, endDate : string, } & DB.ChangeType} { startDate, endDate, changeType } 开始时间与结束时间以及变动类型 时间格式同 date
 * @return.data 结果打卡列表 
 */
export async function queryRecordList({ startDate, endDate } : { startDate : string, endDate : string, }) : Promise<Array<DB.RecordItem>> {
	if (!getDBReady()) return null;
	const res = await batchDate({ startDate, endDate });
	if (res.length) {
		return await Promise.allSettled(res.map(({ dateId, date }) => queryClockRecord(dateId).then(ar => ar?.map(v => ({
			...v,
			date
		}))))).then(arr => arr.reduce((t, v) => t.concat(v ?? []), []))
	} else {
		return []
	}
}